﻿package 
{

	import flash.display.MovieClip;
	import flash.text.*;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.events.KeyboardEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.FileReference;
	import flash.filesystem.*;
	import flash.display.Loader;
	import flash.ui.Mouse;
	import flash.errors.IOError;



	public class sj extends MovieClip
	{

		public var md:Array = new Array  ;
		var i:int = 0;
		public var txt:TextField;
		private var isDown:Boolean;
		private var max:Number;
		private var channel:Number = 5;// 抽奖数目
		private var rk:Array;//通道
		private var fileStream:FileStream;
		private var file:File;
		private var mc1:MovieClip;//通道容器
		private var xb:Array;//存储随机抽出的名单下标
		private var isjx:Number = 0;//中奖的名单是否继续参与抽奖 默认不参与
		private var round:Number = 1;//第几轮
		private var jp:Number = 5;//几等奖
		private var goodsname:Array;//奖品名称
		private var mark:String;//导出时间标记


		public function sj()
		{
			try
			{
				file = File.documentsDirectory.resolvePath("./中奖名单.csv");//创建中奖用户名单
				fileStream= new FileStream();
				fileStream.open(file,FileMode.APPEND);
			}
			catch (error:IOError)
			{
				trace("error"+error.message);
			}
			var ft:String = "奖项,用户,手机,区域,地址,经销商,第几轮,时间标记\r\n";
			fileStream.writeMultiByte(ft,File.systemCharset);
			fileStream.close();
			ft = null;
			//监听通道;


			var date:Date = new Date();
			var month:int = date.getMonth() + 1;
			mark = date.getFullYear() + "年" + month + "月" + date.getDate() + "日";
			td.addEventListener(KeyboardEvent.KEY_UP,checkChannel);
			rank.addEventListener(KeyboardEvent.KEY_UP,goods);
			//配置通道容器 
			mc1 = new MovieClip  ;
			addChild(mc1);
			//建立通道
			setChannel();
			//配置奖品名称
			config();

			//点击抽奖按钮
			bt1.addEventListener(MouseEvent.MOUSE_DOWN,how);

			bt1.visible = false;
			//载入队列  远程属于 请使用loadData
			bt2.addEventListener(MouseEvent.MOUSE_DOWN,localLoad);
			


		}
		public function config():void
		{
			var config:File = File.applicationDirectory.resolvePath("config.xml");
			var stream:FileStream = new FileStream  ;
			stream.open(config,FileMode.READ);
			var str:XML = XML(stream.readMultiByte(config.size,File.systemCharset));
			stream.close();
			goodsname=new Array();
			isjx = str.isloop;
			for (var i in str.gname)
			{
				goodsname.push(str.gname[i]);
			}
			ts.text = "配置文件载入成功";


		}

		//建立抽奖通道 增加背景图
		public function setChannel():void
		{

			txt = new TextField  ;
			//批量生成抽奖输入口 舞台宽度为800
			rk = new Array  ;
			var j:int = 0;
			var lev:int = 0;
			var format:TextFormat = new TextFormat  ;
			format.size = 18;
			format.font = "宋体";
			format.color = 0x333333;

			for (var i=1; i<=channel; i++)
			{
				rk[i] = new TextField  ;
				//2个一行
				if (i%2==0)
				{
					j = 1;
				}
				else
				{
					j = 0;
					lev++;

				}
				rk[i].background = true;
				rk[i].backgroundColor = 0xFFFFFF;
				rk[i].width = 300;
				rk[i].height = 40;
				rk[i].border = true;
				rk[i].borderColor = 0xFFFFFF;
				rk[i].defaultTextFormat = format;;
				rk[i].x = 80 + (320 * j);
				rk[i].y = 220 + (lev * 50);
				rk[i].text = "通道" + i;
				mc1.addChild(rk[i]);
			}


		}


		public function checkChannel(e:KeyboardEvent):void
		{
			var k:TextField;
			for (var i=1; i<=channel; i++)
			{
				k = rk[i];
				mc1.removeChild(k);
			}
			channel = Number(td.text);

			setChannel();

		}

		public function localLoad(e:MouseEvent):void
		{
			var f:File = File.applicationDirectory;
			f = f.resolvePath("./list.csv");
			var fstream:FileStream = new FileStream  ;
			fstream.open(f,FileMode.READ);
			var str:String = fstream.readMultiByte(f.size,File.systemCharset);
			var tags:Array = str.split("\n");

            tags.splice(0,1);//删除第一行数据
			tags.splice(tags.length-1,1);//删除最后一行
			//处理手机号码
		     var myPattern:RegExp = /(\d{3})(\d{4})/;
            var pattern2:RegExp=/(\d{11})+/g;
		  
			for (var i in tags)
			{
				//删除空白行
				md[i] = tags[i].replace(/^\s*|\s*$/g,"");
				var mobile=md[i].match(pattern2);
			 
			    md[i]= md[i].replace(myPattern,"$1****");
				md[i]=md[i]+","+mobile;
		  }

			fstream.close();
			max = md.length;
			ts.text = "数据载入成功";
			//显示开始按钮
			bt2.visible = false;
			bt1.visible = true;
		}

		//加载数据 远程和本地都可以
		public function loadData(e:MouseEvent):void
		{
			var targetURL:String = "./list.txt";
			var request:URLRequest = new URLRequest(targetURL);

			var loader:URLLoader=new URLLoader();
			loader.dataFormat = URLLoaderDataFormat.TEXT;
			loader.addEventListener(Event.COMPLETE,completeHandler);

			try
			{
				trace("loading...");
				loader.load(request);
			}
			catch (error:Error)
			{
				trace("unable to load URL:"+error);
			}

		}

		public function completeHandler(event:Event):void
		{

			var tags:Array = event.target.data.split("\n");
			//只需要第1,2,3行
			for (var i in tags)
			{
				md[i] = tags[i].replace(/^\s*|\s*$/g,"");
			}
			max = md.length - 1;
			ts.text = "数据载入成功";
			//显示开始按钮
			bt2.visible = false;
			bt1.visible = true;
		}

		public function goods(e:KeyboardEvent):void
		{
			var id:Number = Number(rank.text);
			var ldr:Loader = new Loader();
			var url:String = "./goods/" + id + ".png";

			var urlReq:URLRequest = new URLRequest(url);
			round = 1;
			jp = id;

			ts.text = "设置奖项为" + id + "等奖 " + goodsname[id - 1];

			ldr.load(urlReq);
			jpq.addChild(ldr);


		}

		public function how(e:MouseEvent):void
		{
			if (! isDown)
			{
				bt1.gotoAndStop(2);
				ts.text = "正在抽" + jp + "等奖" + goodsname[jp - 1] + ",第" + round + "轮";

				addEventListener(Event.ENTER_FRAME,jump);

			}
			else
			{
				//抽奖成功
				bt1.gotoAndStop(1);
				var k:Number = Number(rank.text);
				if (jp!=k)
				{
					round = 1;
				}
				else
				{
					jp = k;

					ts.text = "已完成" + jp + "等奖" + goodsname[jp - 1] + ",第" + round + "轮";

					round++;
				}
				jp = k;

				getLuckUser(jp);

				removeEventListener(Event.ENTER_FRAME,jump);
			}
			isDown = ! isDown;
		}

		//获取抽奖用户 写入文本
		public function getLuckUser(price:Number):void
		{

			fileStream.open(file, FileMode.APPEND);

			//停止一次只写入一次;
			var info:String = "";
			//存储在当前内存中的号码
			for (var i=0; i<xb.length; i++)
			{
				info +=  price + "," + md[xb[i]] + "," + goodsname[jp - 1] + "," + round + "," + mark + "\r\n";

			}
			

			fileStream.writeMultiByte(info,File.systemCharset);
			fileStream.close();
			//删除中奖名单;
			var flag=false;
			if (isjx<1)
			{
                //每删除一个 这个时候的md的值已经发生了变化
				   //测试  结果是 bb dd ff
				   var rs=new Array;
				for(i=0;i<md.length;i++){
					 for(var j=0;j<xb.length;j++){
						
						if(i==xb[j]){
							flag=true;
							
						}
				    }
					if(!flag){
				   rs.push(md[i]);
				  
				  }
				  flag=false;

				}
				
				md=rs;
				rs=[];  
				max = md.length;//新的队列长度

			}
			
						

		}

		//获取不重复的随机数字 指针
		public function num():Array
		{
			var num:Array = new Array  ;
			var current:Number;//存储已经产生的号码
			var flag:Boolean = false;

			if (max<channel)
			{
				ts.text = "剩余名单不足";
				bt1.visible = false;
				return num;
			}

			for (var i=0; i<channel; i++)
			{
				current = Math.floor(Math.random() * max);

				//进行比较
				for (var j=0; j<num.length; j++)
				{
					if (current==num[j])
					{
						i--;
						flag = true;
						break;
					}

				}

				if (flag)
				{
					flag = false;
					continue;


				}
				num[i] = current;
			}
			return num;

		}

		//对通道进行显示
		public function jump(e:Event):void
		{

			xb = num();
			var k:Array = new Array  ;
			var xm:String;
			var mobile:String;
			var area:String;
			for (var i=1; i<=channel; i++)
			{

				k = md[xb[i - 1]].split(",");
				rk[i].text =  k[0] +  k[1] + k[2];
			}

		}
	}

}